package com.springcloud.config;

import com.alibaba.fastjson.JSONArray;
import com.springcloud.commom.api.R;
import com.springcloud.commom.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class ServerProtectInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(HandlerInterceptor.class);


    @Override
    public boolean preHandle( HttpServletRequest request,  HttpServletResponse response,  Object handler) throws Exception {
        if (!CommonConstant.ONLY_FETCH_BY_GATE_WAY) {
            return true;
        }

        String tk = request.getHeader("gateway");
        String gatewayToken = new String(Base64Utils.encode("keys".getBytes()));

        if (StringUtils.equals(gatewayToken, tk)) {
            return true;
        } else {
            R resultData = new R();
            resultData.setCode(HttpServletResponse.SC_FORBIDDEN);
            resultData.setMsg("请通过网关访问资源");

            PrintWriter out = getOut(response);
            out.print(JSONArray.toJSONString(resultData));

            return false;
        }
    }

    private PrintWriter getOut(HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        return out;
    }
}

